package com.sicnu.resources.service.impl;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import com.sicnu.resources.service.CosService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PreDestroy;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;

/**
 * @author 怨九己
 */
@Service
public class CosServiceImpl implements CosService {

    private static final Logger logger =
            LoggerFactory.getLogger(CosServiceImpl.class);

    private final COSClient cosClient;
    private final TransferManager transferManager;

    @Autowired
    public CosServiceImpl(COSClient cosClient) {
        this.cosClient = cosClient;
        // 初始化 TransferManager，使用默认线程池
        this.transferManager = new TransferManager(cosClient);
    }

    @Override
    public String uploadObject(
            String bucketName,
            String key,
            MultipartFile file) throws IOException {
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(
                            bucketName,
                            key,
                            file.getInputStream(),
                            metadata);
            cosClient.putObject(putObjectRequest);
            return "上传成功";
        } catch (CosClientException e) {
            logger.error("上传失败", e);
            return "上传失败";
        }
    }

    @Override
    public void deleteObject(String bucketName, String key) {
        try {
            DeleteObjectRequest deleteObjectRequest =
                    new DeleteObjectRequest(bucketName, key);
            cosClient.deleteObject(deleteObjectRequest);
            logger.info("Delete Object Success!");
        } catch (CosClientException e) {
            logger.error("Delete Object Failed", e);
        }
    }


    @Override
    public URL generatePresignedUrl(String bucketName, String key) {
        try {
            GeneratePresignedUrlRequest generatePresignedUrlRequest =
                    new GeneratePresignedUrlRequest(bucketName, key);
            generatePresignedUrlRequest.setExpiration(
                    java.util.Date.from(
                            java.time.Instant.now().plusSeconds(3600)));
            return cosClient.generatePresignedUrl(generatePresignedUrlRequest);
        } catch (CosClientException e) {
            logger.error("Generate Presigned URL Failed", e);
            return null;
        }
    }

    @Override
    public List<COSObjectSummary> searchObjects(String bucketName, String key) {
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        listObjectsRequest.setBucketName(bucketName);
        listObjectsRequest.setPrefix(key);
        try {
            ObjectListing objectListing =
                    cosClient.listObjects(listObjectsRequest);
            return objectListing.getObjectSummaries();
        } catch (CosClientException e) {
            logger.error("Search Objects Failed", e);
            return null;
        }
    }

    @Override
    public String uploadLargeFile(String bucketName, String key, File file) {
        try {
            Upload upload = transferManager.upload(bucketName, key, file);
            UploadResult uploadResult = upload.waitForUploadResult();
            logger.info("Upload large file success, ETag: {}",
                    uploadResult.getETag());
            return "上传成功";
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error("Upload large file interrupted", e);
            return "上传失败";
        } catch (CosClientException e) {
            logger.error("Upload large file failed", e);
            return "上传失败";
        }
    }

    @PreDestroy
    public void shutdownTransferManager() {
        // 在应用程序关闭时关闭 TransferManager
        transferManager.shutdownNow();
        logger.info("TransferManager has been shut down.");
    }

}